package com.tnl.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biz.hunter.dao.CompanyDAO;
import com.biz.hunter.dao.EmployeeDAO;
import com.biz.hunter.dao.HunterDAO;
import com.biz.hunter.dao.InterViewDAO;
import com.biz.hunter.dao.JobDAO;
import com.biz.hunter.dao.PersonDAO;
import com.biz.hunter.dao.RecommendDAO;
import com.biz.hunter.db.entity.Company;
import com.biz.hunter.db.entity.Employee;
import com.biz.hunter.db.entity.Hunter;
import com.biz.hunter.db.entity.Interview;
import com.biz.hunter.db.entity.JobDesc;
import com.biz.hunter.db.entity.Person;
import com.biz.hunter.db.entity.Recommendation;
import com.tnl.web.dto.jqGridRequestObject;
import com.tnl.web.dto.jqGridResponseObject;
import com.tnl.web.entity.ErrorMsg;
import com.tnl.web.util.qualifiers.AuditIt;

/**
 * Handles requests for the Recommendation service.
 */
@Controller
public class RecommendController {

	private static final Logger logger = LoggerFactory.getLogger(RecommendController.class);

	@Autowired
	private RecommendDAO recommendDAO;
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private JobDAO jobDAO;
	@Autowired
	private PersonDAO personDAO;
	@Autowired
	private EmployeeDAO employeeDAO;
	@Autowired
	private HunterDAO hunterDAO;
	@Autowired
	private InterViewDAO interviewDAO;

	// 推荐管理首页
	@AuditIt(module = "Recommend", action = "recommend_view", description = " show Recommend index page")
	@RequestMapping(value = "admin/recommend/manage.page", method = RequestMethod.GET)
	public String jobManagement(HttpServletRequest request, ModelMap model) {
		return "admin/recommend/recommendlist";
	}
	
	// 推荐详细信息及面试列表首页
	@RequestMapping(value = "admin/recommend/detail.page", method = RequestMethod.GET)
	public String interviewManagment(HttpServletRequest request, ModelMap model, String rdid) {
		
		if(StringUtils.isEmpty(rdid)) {
			return "admin/errorpage";
		}
		Recommendation rd = recommendDAO.getById(rdid);
		Person person = personDAO.getById(rd.getPersonId());
		JobDesc job = jobDAO.getById(rd.getJobId());
		
		int createby = rd.getCreateby();
		int platformid = rd.getPlatformId();
		String createPerson = null;
		Employee emp = null;
		Hunter hunter = null;
		if(platformid == 1) {
			emp = employeeDAO.getByPersonId(createby);
			createPerson = emp.getName();
		} else {
			hunter = hunterDAO.getById(createby);
			createPerson = hunter.getName();
		}
		
		model.addAttribute("recommend", rd);
		model.addAttribute("person", person);
		model.addAttribute("job", job);
		model.addAttribute("createperson", createPerson);
		
		return "admin/recommend/interviewlist";
	}

	// 搜索数据
	@RequestMapping(value = "admin/recommend/search.do", method = RequestMethod.POST)
	public @ResponseBody jqGridResponseObject<Recommendation> searchRecommend(
			jqGridRequestObject request, String sname,
			Integer sstatus) {
			
		jqGridResponseObject<Recommendation> msg = new jqGridResponseObject<Recommendation>();
			
		long page = request.getPage();
		long pagesize = request.getRows();
			
		long totalrows = request.getTotalrows();
		long totalpages = 0;
			
		// 需要分页和计算总数
		if(totalrows == 0) {
			totalrows = recommendDAO.getCountOfAll(sname,sstatus);
		}

		totalpages = jqGridResponseObject.calTotalPage(totalrows, pagesize);
			
		// 起始位置
		long start = 0;
		start = (page-1) * pagesize;

		// 获取数据
		List<Company> companies = companyDAO.getALL();
		List<Recommendation> list = recommendDAO.getAllWithLimit(sname, sstatus , start, pagesize);
		if(list != null) {
			for (Recommendation rd : list) {
				if(rd.getStatus() ==0) {
					rd.setStatusStr("面试邀请待批准");
				} else if(rd.getStatus() ==1) {
					rd.setStatusStr("推荐中");
				} else if(rd.getStatus() ==2) {
					rd.setStatusStr("推荐成功");
				} else {
					rd.setStatusStr("推荐失败");
				}
				JobDesc job = jobDAO.getById(rd.getJobId());
				rd.setJobName(job.getName());

				for(Company cp : companies) {
					if(job.getCompanyId() == cp.getId()) {
						rd.setCompanyName(cp.getName());
					}
				}
				
				Person person = personDAO.getById(rd.getPersonId());
				if(person !=null){
				rd.setPersonName(person.getName());}
			}
		}
			
		// 设置返回的数据
		msg.setPage(page);
		msg.setTotal(totalpages);
		msg.setRecords(totalrows);
		msg.setRows(list);
			
		return msg;
	}
			
	// 搜索数据
	@RequestMapping(value = "admin/interview/search.do", method = RequestMethod.POST)
	public @ResponseBody jqGridResponseObject<Interview> searchInterview(
			jqGridRequestObject request, Integer sstatus, Integer inid) {
			
		jqGridResponseObject<Interview> msg = new jqGridResponseObject<Interview>();
			
		long page = request.getPage();
		long pagesize = request.getRows();
			
		long totalrows = request.getTotalrows();
		long totalpages = 0;
			
		// 需要分页和计算总数
		if(totalrows == 0) {
			totalrows = interviewDAO.getCountOfAll(inid, sstatus);
		}

		totalpages = jqGridResponseObject.calTotalPage(totalrows, pagesize);
			
		// 起始位置
		long start = 0;
		start = (page-1) * pagesize;

		// 获取数据
		List<Interview> list = interviewDAO.getAllWithLimit(inid,sstatus, start, pagesize);
		if(list != null) {
			for (Interview itv : list) {
				int itype = itv.getItype();
				int status = itv.getStatus();
				java.sql.Date updateTime = itv.getUpdateTime();
				String itypeStr = null;
				String statusStr = null;
				String updateStr = null;
				switch(itype) {
					case 1:
						itypeStr = "电话面试";
						break;
					case 2:
						itypeStr = "公司面试";
						break;
					case 3:
						itypeStr = "笔试";
						break;
					case 4:
						itypeStr = "业务面试";
						break;
					case 5:
						itypeStr = "人事面试";
						break;
					default:
						itypeStr = "电话面试";
						break;
				}
				itv.setItypeStr(itypeStr);
				switch(status) {
					case 1:
						statusStr = "已发面试邀请";
						break;
					case 2:
						statusStr = "建议继续面试";
						break;
					case 3:
						statusStr = "拒绝";
						break;
					case 4:
						statusStr = "录用";
						break;
					case 5:
						statusStr = "奖金已发放";
						break;
					default:
						statusStr = "已发面试邀请";
						break;
				}
				itv.setStatusStr(statusStr);
				updateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(updateTime);
				itv.setTimeStr(updateStr);
			}
		}
			
		// 设置返回的数据
		msg.setPage(page);
		msg.setTotal(totalpages);
		msg.setRecords(totalrows);
		msg.setRows(list);
			
		return msg;
	}
	
	@RequestMapping(value = "admin/recommend/update.do", method = RequestMethod.GET)
	public @ResponseBody ErrorMsg updateRecommendation(HttpServletRequest request, Integer rdid) {
		logger.info("Start UPDATE Recommendation.");
		ErrorMsg msg = new ErrorMsg();
		
		if (rdid == null) {
			logger.debug("inid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除数据");	
			return msg;
		}
		
		Recommendation recommend = recommendDAO.getById(String.valueOf(rdid));
		if(recommend == null) {
			logger.debug("inid is null");
			msg.setErrorcode("-1");
			msg.setMsg("必须指定要删除数据");	
			return msg;
		}
		
		// 设置为允许推荐 -> 面试邀请确认
		recommend.setStatus(1);
		
		int result =recommendDAO.update(recommend);
		if (result == -1) {
			msg.setErrorcode("50001");
			msg.setMsg("can not update the recommend" + recommend.getId());
			return msg;
		}
		msg.setErrorcode("0");
		msg.setMsg("success");

		return msg;
	}
	
	
	/*
	@RequestMapping(value = "admin/recommend/toView.do", method = RequestMethod.GET)
	public @ResponseBody Recommendation getRecommendation(
			String Id) {
		logger.info("Start getRecommendation. ID=" + Id);
		Recommendation emp = recommendService.getById(Id);
		int id = emp.getPersonId();
		Person candidate = personDAO.getById(id);
		emp.setPerson(candidate);
		return emp;
	}

	@RequestMapping(value="admin/recommend/manage.do", method = RequestMethod.GET)
	public @ResponseBody List<Recommendation> getAllRecommendations() {
		logger.info("Start getAllRecommendations.");
		List<Recommendation> recommends = recommendService.getALL();
		return recommends;
	}

	@RequestMapping(value = "admin/recommend/create.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg createRecommendation(
			@RequestBody Recommendation recommend) {
		logger.info("Start create Recommendation.");
		ErrorMsg msg = new ErrorMsg();
		Date now = new Date();
		recommend.setCreateDate(now.getTime());
		int result = recommendService.save(recommend);
		if (result == -1) {
			msg.setErrorcode("50001");
			msg.setMsg("can not save the recommend" + recommend.getId());
			return msg;
		}
		msg.setErrorcode("0");
		msg.setMsg("success");

		return msg;
	}

	@RequestMapping(value = "admin/recommend/delete.do", method = RequestMethod.DELETE)
	public @ResponseBody ErrorMsg deleteRecommendation(
			@PathVariable("id") String id) {
		logger.info("Start deleteRecommendation.");
		ErrorMsg msg = new ErrorMsg();
		Recommendation emp = recommendService.getById(id);
		int result = recommendService.delete(id);
		if (result == -1) {
			msg.setErrorcode("50001");
			msg.setMsg("can not delete the recommend" + id);
			return msg;
		}
		msg.setErrorcode("0");
		msg.setMsg("success");

		return msg;
	}

	@RequestMapping(value = "admin/recommend/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateRecommendation(
			@RequestBody Recommendation recommend) {
		logger.info("Start UPDATE Recommendation.");
		ErrorMsg msg = new ErrorMsg();
		int result =recommendService.update(recommend);
		if (result == -1) {
			msg.setErrorcode("50001");
			msg.setMsg("can not delete the recommend" + recommend.getId());
			return msg;
		}
		msg.setErrorcode("0");
		msg.setMsg("success");

		return msg;
	}
	*/
}
